﻿namespace Blaze.UI
{
    using System.Collections.Generic;
    using UnityEngine;

    [ExecuteInEditMode]
    [RequireComponent(typeof(Canvas))]
    public class UILayer : MonoBehaviour
    {
        public int Order
        {
            get => order;
            set
            {
                if (order == value)
                    return;
                order = value;
                update();
                updateChildren();
            }
        }

        public void Add(UILayerOrder child)
        {
            if (mChildren.Add(child))
                child.UpdateLayer();
        }

        public void Remove(UILayerOrder child)
        {
            mChildren.Remove(child);
        }

        private void Awake()
        {
            mCanvas = GetComponent<Canvas>();
        }

        private void Start()
        {
            update();
        }

        private void update()
        {
            mCanvas.sortingOrder = order;
            mCanvas.planeDistance = 1000 - order;
        }

        private void updateChildren()
        {
            foreach (var child in mChildren)
                child.UpdateLayer();
        }

        private Canvas mCanvas;

        [SerializeField]
        [Tooltip("UI层级")]
        private int order;

        private readonly HashSet<UILayerOrder> mChildren = new HashSet<UILayerOrder>();
    }
}